package org.netty.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;


public class ServerChannleInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        System.out.println("报告");
        System.out.println("信息：有一客户端链接到本服务端");
        System.out.println("IP:" + socketChannel.localAddress().getHostName());
        System.out.println("Port:" + socketChannel.localAddress().getPort());
        System.out.println("报告完毕");

        /*
         * 使用 weakCachingConcurrentResolver 创建线程安全的 WeakReferenceMap,
         * 对类加载器进行缓存,它支持多线程并发访问,当虚拟机内存不足时,会释放缓存中的内存,
         * 防止内存泄露,为了房子异常码流和解码错位导致的内存溢出,
         * 这里将单个对象序列化之后的字节数组长度设置为1M
         */
        ObjectDecoder objectDecoder = new ObjectDecoder(1024 * 1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader()));

        //序列化、编码
        pipeline.addLast(new ObjectEncoder());
        //序列化、解码
        pipeline.addLast(objectDecoder);
        pipeline.addLast(new NettyServerHandler());
    }
}
